import React, { useEffect, useRef } from 'react'
import { useState } from 'react'
import { Button, Select, Form, Input, Steps, notification } from 'antd'
import './newsAdd.css'
import style from './News.module.css'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import axios from 'axios'
import { useNavigate, useLocation } from 'react-router-dom'

const { Option } = Select

export default function NewsAdd() {
  const [current, getcurrent] = useState(0)
  const [optionList, setoptionList] = useState([])
  const [text, getText] = useState({})
  const [title, setTitle] = useState({})
  const User = JSON.parse(localStorage.getItem('token'))

  const navigator = useNavigate()
  let location = useLocation()
  const NewsForm = useRef(null)
  const contentForm = useRef(null)

  useEffect(() => {
    //判断新编辑还是修改
    if (location.state !== null && location.state.id !== undefined ) {
      axios
        .get(`/news/${location.state.id}?_expand=category&_expand=role`)
        .then((res) => {
          let { title, categoryId, content } = res.data
          NewsForm.current.setFieldsValue({
            title,
            categoryId,
          })
          contentForm.current.setFieldsValue({
            text: content,
          })
        })
    }
    axios.get('/categories').then((res) => {
      setoptionList(res.data)
    })
  }, [])
  const saveText = (value) => {
    getcurrent(2)
    getText(value)
  }
  const onBack = () => {
    getcurrent(current - 1)
  }
  const onFinish = (value) => {
    setTitle(value)
    getcurrent(1)
  }
  //保存草稿0/提交审核1
  const saveNews = (auditState) => {
    if (location.state !== null && location.state.id !== undefined ) {
      axios
        .patch(`/news/${location.state.id}`, {
          ...title,
          content: text.text,
          region: User.region ? User.region : '全球',
          author: User.username,
          roleId: User.roleId,
          auditState: auditState,
          publishState: 0,
          createTime: Date.now(),
          star: 0,
          view: 0,
        })
        .then((res) => {
          notification.info({
            message: `通知`,
            description: `您可以到${
              auditState === 0 ? '草稿箱' : '审核列表'
            }中查看您的新闻`,
            placement: 'bottomRight',
          })
          setTimeout(() => {
            navigator(
              auditState === 0 ? '/news-manage/draft' : '/audit-manage/list',
            )
          }, 3000)
        })
    } else {
      axios
        .post('/news', {
          ...title,
          content: text.text,
          region: User.region ? User.region : '全球',
          author: User.username,
          roleId: User.roleId,
          auditState: auditState,
          publishState: 0,
          createTime: Date.now(),
          star: 0,
          view: 0,
        })
        .then((res) => {
          notification.info({
            message: `通知`,
            description: `您可以到${
              auditState === 0 ? '草稿箱' : '审核列表'
            }中查看您的新闻`,
            placement: 'bottomRight',
          })
          setTimeout(() => {
            navigator(
              auditState === 0 ? '/news-manage/draft' : '/audit-manage/list',
            )
          }, 3000)
        })
    }
  }

  return (
    <div>
      <Steps
        current={current}
        items={[
          {
            title: '基本信息',
            description: '新闻标题，新闻分类',
          },
          {
            title: '新闻内容',
            description: '新闻主体内容',
          },
          {
            title: '新闻提交',
            description: '保存草稿或者提交审核',
          },
        ]}
      />
      <div className="activeBox">
        <div className={current === 0 ? '' : style.active}>
          <Form
            name="basic"
            onFinish={onFinish}
            autoComplete="off"
            ref={NewsForm}
          >
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入新闻标题!',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[
                {
                  required: true,
                  message: '请输入新闻分类!',
                },
              ]}
            >
              <Select showSearch>
                {optionList.map((o) => {
                  return <Option value={o.id}>{o.title} </Option>
                })}
              </Select>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                下一步
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className={current === 1 ? '' : style.active}>
        <Form onFinish={saveText} autoComplete="off" ref={contentForm}>
          <Form.Item
            label="新闻内容"
            name="text"
            rules={[
              {
                required: true,
                message: '请输入新闻内容!',
              },
            ]}
          >
            <ReactQuill theme="snow" />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            下一步
          </Button>
          <Button onClick={onBack}>上一步</Button>
        </Form>
      </div>
      <div className={current === 2 ? '' : style.active}>
        <Button type="primary" onClick={() => saveNews(0)}>
          保存草稿
        </Button>
        <Button type="primary" danger onClick={() => saveNews(1)}>
          提交审核
        </Button>
        <Button onClick={onBack}>上一步</Button>
      </div>
    </div>
  )
}
